{-# LANGUAGE DeriveDataTypeable #-}

module Language.Dependencies.Adaptors.ASTExpr
  ( languageexpr
  , module Language.ASTExpr.Syntax
  , module Language.ASTExpr.Parser
  , module Language.ASTExpr.Eval
  , module Language.ASTExpr.ASTExpr
  ) where

-- container
import Data.Tree (Tree(Node,rootLabel))


-- local imports
import Language.Dependencies.Language
import Language.Dependencies.Term2tree (data2tree)

import Language.ASTExpr.Syntax
import Language.ASTExpr.Eval
import Language.ASTExpr.Parser
import Language.ASTExpr.ASTExpr
 
languageexpr = Language {
    name=  "ASTExpr" 
  , syntax = []
  , exts = [".ast"] 
  , parse = parseASTExpr
  , toTree = (data2tree TheExpr :: Expr -> Tree String)
  , srcLoc       = toSrcLoc
  , adjustSrcLoc = Nothing
  , srcLoctype   = (Coordinate undefined undefined) 
  , typerep = Just (TheExpr)
  }
    
parseASTExpr :: String -> Either Error Expr
parseASTExpr s = case (fromString s) of
   Right expr -> Right expr
   Left msg   -> Left (ErrMessage msg)

toSrcLoc :: Tree String -> [Loc]
toSrcLoc (Node "SrcSpan" [ srcFrom, srcTo ]  ) = return $ Coordinate (fst $ extract srcFrom, snd $ extract srcFrom) (fst $ extract srcTo, snd $ extract srcTo) 
toSrcLoc _ = []

extract (Node (srcSpan) cs ) = ((read line :: Int),(read column :: Int))
                               where
                                 srcLoc = words srcSpan
                                 line = init (srcLoc !! 2)
                                 column = init (srcLoc !! 4)
